using System;
using System.Net;
using System.Threading;
using MFWebSockets.Core.Contract.Delegates;
using MFWebSockets.Core.Contract.Enums;
using MFWebSockets.Core.Contract.EventArgs;
using MFWebSockets.Core.Contract.Interfaces;

namespace MFWebSockets.Core.Clients
{
    public class MockWebSocketClient : IWebSocketClient
    {
        public MockWebSocketClient(Uri endpoint)
        {
            ConnectionStatus = ConnectionStatus.Disconnected;
            Close += OnClose;
            Open += OnOpen;
        }

        private void OnOpen(IWebSocketClient sender)
        {
            ConnectionStatus = ConnectionStatus.Connected;
        }

        private void OnClose(IWebSocketClient sender)
        {
            ConnectionStatus = ConnectionStatus.Disconnected;
        }

        public event OpenHandler Open;
        public event CloseHandler Close;
        public event MessageHandler Message;
        public ConnectionStatus ConnectionStatus { get; set; }


        public void Send(string message)
        {
            Thread.Sleep(1000);
        }

        public void Connect()
        {
            ConnectionStatus = ConnectionStatus.Connecting;

            new Thread(GenerateMessages).Start();

            Thread.Sleep(1000);

            Open(this);
        }

        public void Disconnect()
        {
            ConnectionStatus = ConnectionStatus.Disconnecting;

            Thread.Sleep(1000);

            Close(this);
        }

        private void GenerateMessages()
        {
            var i = 0;
            while (true)
            {
                if (Message != null)
                    Message(this, new MessageArgs
                                      {
                                          Message = "Test message " + i
                                      });
                i++;
                Thread.Sleep(1000);
            }

        }

    }
}